package com.dz51.core.validate.validator.strategy;  

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import com.dz51.core.validate.annotation.ParamValidater;
import com.dz51.core.validate.util.ValidateResultBulider;
import com.dz51.core.validate.vo.ValidateResult;
  
public class RegexValidator extends ValidateModel{

    @Override
    public ValidateResult validate(HttpServletRequest request, ParamValidater paramValidater) {
        if(request == null || paramValidater.name() == null){
            return ValidateResultBulider.createNoReasonFailResult(request);
        }
        String param = request.getParameter(paramValidater.name());
        
        //验证前需要和not null相兼容；即：如果有not null，再进行验证，否则在参数为null时不进行验证直接 return true
        boolean canNull = paramValidater.nullable();
        if(canNull && (param == null || param.length() == 0)){
          return  ValidateResultBulider.createSuccessResult(request); 
        }
        
        if(param == null || param.length() == 0){
            return ValidateResultBulider.createNoReasonFailResult(request);
        }
        
        Pattern regex = Pattern.compile(paramValidater.regex());
        Matcher matcher = regex.matcher(param);
        boolean isMatched = matcher.matches();
        
        if(!isMatched){
            return ValidateResultBulider.createNoReasonFailResult(request);
        }
        return ValidateResultBulider.createSuccessResult(request);

    }

}
